import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import * as dict from '@/services/dict';
import { t } from '@lingui/macro';

export default class BusStationStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };

  _other_args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };

  total = 0;
  other_total = 0;

  _region = {}; // 选中的区域
  regionData = []; // 城市数据
  stations = [];
  other_stations = [];
  params = {
    cityId: '',
    cityName: '',
    type: '',
  };
  selectStation = [];
  selectStationInfos = [];
  currentStationInfos = [];
  stationInfo = {};

  loading = false;
  other_loading = false;

  _stationType = '0';

  _relate = false;

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false, _region: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { fullId = '' } = this._region || {};
    const parts = fullId.split(':');

    if (parts.length === 1) {
      _.assign(this._args.search, { cityIds: fullId ? [fullId] : [] });
      _.unset(this._args.search, 'areaName');
    } else if (parts.length === 2) {
      _.set(this._args.search, 'areaName', parts[1]);
    }

    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;

    this.loading = true;
    try {
      this.total = yield api.count({ search });
      const stations = yield api.search({ search, pg });
      this.stations = stations;
    } finally {
      this.loading = false;
    }
  }

  * query_other(pgInfo) {
    _.mergeWith(this._other_args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._other_args);
    search.related = this._relate;
    if (this._stationType === '1') {
      search.stationLongLat = this.stationInfo?.longLat;
      search.range = search.range || 0;
    }
    if (!pg.sort?.length) delete pg.sort;

    this.other_loading = true;
    try {
      this.other_total = this._stationType === '0' ? yield api.getStationOtherCount({ search }) : 10;
      const res = this._stationType === '0' ? yield api.getStationOther({ search, pg }) : yield api.getRecommendStation(search);
      this.other_stations = res;
      this.other_stations = res.map((p) => ({
        ...p,
        proKey: `${p.companyId}-${p.stationId}`,
      }));
    } finally {
      this.other_loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * _reload() {
    yield this.query();
  }

  * update(station) {
    yield api.update(station);
    yield this._reload(station);
  }

  * create(station) {
    yield api.create(station);
    yield this._reload(station);
  }

  * remove(station) {
    yield api.remove(station.itemId);
    yield this._reload(station);
  }

  * updateState(station) {
    station.state = !station.state;
    yield api.update(station);
    yield this.query();
  }

  async existsValidator(rule, value) {
    if (!value) return Promise.resolve();
    try {
      const item = await api.get(value); // 注意get不存在时会抛出404异常
      if (item) return Promise.reject(new Error(t`${value}已存在`));
    } catch (_) {
      return Promise.resolve();
    }
  }

  isDictrict() { // 当前选中区域是否行政区
    // console.log('this._region', this._region, this._region?.fullId?.indexOf(':'));
    if (!this._region?.fullId) return false;
    return this._region?.fullId?.indexOf(':') !== -1;
  }

  * getCity(args) {
    const res = yield api.allRegions(args);
    const regions = res.map((p) => ({ label: p.result, value: p.result }));
    return regions;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  _other_idx(i) {
    return this._other_args.pg.page * this._other_args.pg.size + i + 1;
  }

  currentIdx(i, page, size) {
    return page * size + i + 1;
  }

  * getCompany(args) {
    const res = yield api.getCompany(args);
    const toggleCompanys = res.map((p) => ({ label: p.name, value: p.id }));
    return toggleCompanys;
  }

  * getTopItems(args) {
    const res = yield dict.getTopItems(args);
    return res.map((p) => ({ label: p.name, value: p.itemId }));
  }

  * getRecommendStation(args) {
    const res = yield dict.getRecommendStation(args);
    return res.map((p) => ({ label: p.name, value: p.itemId }));
  }

  * getRoutesInit() {
    yield api.getRoutesInit();
    yield this._reload();
  }

  get relate() {
    return this._relate;
  }

  set relate(r) {
    this._relate = r;
    this.query_other();
  }

  get region() {
    return this._region;
  }

  set region(r) {
    this._region = r;
    this.query();
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get other_pg() {
    return this._other_args.pg;
  }

  set other_pg(pg) {
    this.query_other({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get other_search() {
    this._other_args.pg.page = 0;
    return this._other_args.search;
  }

  set other_search(search) {
    this._other_args.pg.page = 0;
    this._other_args.search = search;
    this.query_other({ page: 0 });
  }

  get stationStatus() {
    return this._stationType;
  }

  set stationStatus(value) {
    this._stationType = value;
    this._args.pg.page = 0;
    this.query_other({ page: 0 });
  }
}
